﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Formatters;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExceptionlessDemo.Filter
{
    public class HttpRequestHelper
    {
        /// <summary>
        /// 异步读取请求Body内容
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static async Task<string> ReadBodyAsync(HttpRequest request)
        {
            string body = "";
            if (request.ContentLength > 0)
            {
                //允许Request反复读取
                request.EnableBuffering();
                using (var reader = new StreamReader(request.Body, GetRequestEncoding(request)))
                {
                    request.Body.Position = 0;// .Seek(0, SeekOrigin.Begin);
                    body = await reader.ReadToEndAsync();
                    request.Body.Position = 0;
                    //request.Body.Seek(0, SeekOrigin.Begin);
                }

            }
            return body;
        }

        /// <summary>
        /// 得到请求的字符集
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static Encoding GetRequestEncoding(HttpRequest request)
        {
            var requestContentType = request.ContentType;
            var requestMediaType = requestContentType == null ? default(MediaType) : new MediaType(requestContentType);
            var requestEncoding = requestMediaType.Encoding;
            if (requestEncoding == null)
            {
                requestEncoding = Encoding.UTF8;
            }
            return requestEncoding;
        }
    }
}
